import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Image, Picker, Input} from '@tarojs/components';
import {AtIcon, AtImagePicker, AtTextarea} from 'taro-ui'
import {newHttp} from "../../../utils/request";
import {
  BASE_URL,
  materialMedia,
  NEW_GET_ORDER_DETAIL,
  TARO_ENV,
  UPLODE_FALE,
  AIKUCUN_ORDER_CREATAFTERSALE
} from "../../../constants/api";
import {GetRequest} from "../../../utils/tools";
import Float from "../../../components/float/float";
import {h5Wx} from "../../../utils/h5.service";
import {http} from "../../../utils/http";
import {lxH5Wx} from "../../../utils/lx.h5.service";
import './refund.scss'

type StateProps = {
  orderInfo: object
  isReceived: any
  formData: any
  refundReason: any
  fileList: any
  fileList1: any
  editShow: boolean
}

export default class Refund extends Component {
  state: StateProps = {
    orderInfo: {},
    isReceived: [{value: '0', label: '未收货(整件漏发)'}, {value: '1', label: '已收货(部分漏发)'}],
    refundReason: [
      {value: '0', label: '不想要了(无理由)'},
      {value: '1', label: '商品漏发'},
      {value: '2', label: '质量问题'},
      {value: '3', label: '发错款号'},
      {value: '4', label: '发错颜色'},
      {value: '5', label: '发错尺码'},],
    formData: {
      application_type: 0,
      is_received: '',
      refund_reason: '',
      description: '',
      pictures: '',
      amount: 0,
      order_num: '',
    },
    fileList: [],
    fileList1: [],
    editShow: false
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV == 'h5') {
      const root = document.querySelector('.taro-tabbar__panel')
      root.style.backgroundColor = '#f3f3f3'
      /*root.onscroll = debounce((page) => {
        this.setState({scrollTop: page[0].target.scrollTop})
      }, 10)*/
    }


    // type: 2漏发退款，4退货退款
    const { orderId, type } = Taro.getCurrentInstance().router.params
    const {formData} = this.state;
    const orderInfo = await newHttp.catchGet(NEW_GET_ORDER_DETAIL, {orderId})
    if (orderInfo) {
      formData.amount = orderInfo.total_fee
      formData.application_type = type
      formData.order_num = orderInfo.order_num
      this.setState({orderInfo: orderInfo})
    }
  }

  onChange(e) {
    const {formData} = this.state;
    formData.is_received = e;
    this.setFormData(formData)
  }
  onChangeReason(e) {
    const {formData} = this.state;
    formData.refund_reason = e;
    this.setFormData(formData)
  }

  setFormData(formData) {
    this.setState({
      formData
    });
  }

  getName(id) {
    const goodsSite = this.state.isReceived.filter(item => item.value == id);
    const label = goodsSite.length > 0 ? goodsSite[0].label : '';
    return label;
  }
  getNameReason(id) {
    const goodsSite = this.state.refundReason.filter(item => item.value == id);
    const label = goodsSite.length > 0 ? goodsSite[0].label : '';
    return label;
  }

  // 上传文件的回调
  onFileChange(fileList?, o?, index?) {
    if (!index && index != 0) {
      this.uploadFile(fileList);
    } else {
      this.setState({
        fileList1: fileList
      })
    }
    if (fileList) {
      this.setState({
        fileList
      });
    }
  }

  // 上传文件
  uploadFile(files, index?) {
    const api = BASE_URL + UPLODE_FALE
    const that = this
    if (TARO_ENV === 'h5') {
      if (process.env.P_ENV === 'lx') {
        lxH5Wx.chooseImage(async (f, length) => {
          lxH5Wx.uploadFile(f, length, (data) => {
            let {fileList1, fileList} = this.state;
            fileList.push({
              url: data
            });
            fileList1 = JSON.parse(JSON.stringify(fileList));
            this.setState({
              fileList,
              fileList1
            });
          })
        }, 1)
      } else {
        h5Wx.chooseImage(1, async ret => {
          Taro.showToast({
            title: '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          h5Wx.wxuploadImage(ret, async res => {
            const dataRet = await newHttp.catchGet(materialMedia + res, {})
            let {fileList1, fileList} = this.state;
            fileList.push({
              url: dataRet
            });
            fileList1 = JSON.parse(JSON.stringify(fileList));
            this.setState({
              fileList,
              fileList1
            });
            Taro.hideToast();
          })
        })
      }
    } else {
      const header = http.getHeader();
      const user = Taro.getStorageSync("user");
      header.token = user.token;
      const file: any = [];
      // 获取新文件
      const newFile: any = [];
      const oldFile: any = [];
      for (let i = 0; files[i]; i++) {
        if (files[i].url.indexOf('//tmp') == -1) {
          oldFile.push(files[i])
        } else {
          newFile.push(files[i])
        }
      }
      let uploadImgCount = 0;
      for (let i = 0; newFile[i]; i++) {
        setTimeout(() => {
          Taro.showLoading({title: '加载中...'});
          Taro.uploadFile({
            url: api,
            filePath: newFile[i].url,
            name: 'file',
            formData: {
              'imgIndex': i
            },
            header,
            success: function (res: any) {
              uploadImgCount++;
              if (res.statusCode != 200) {
                Taro.showToast({
                  title: res.data,
                  icon: 'none'
                })
                return
              }
              const data: any = JSON.parse(res.data);
              const imageUrl: string = data.imageUrl;
              file.push({
                url: imageUrl
              });
              if (uploadImgCount == newFile.length) {
                let fileList1 = oldFile;
                fileList1 = fileList1.concat(file);
                that.setState({
                  fileList1
                });
              }
              Taro.hideLoading();
            },
            fail: function (res) {
              Taro.hideLoading();
              Taro.showModal({
                title: '错误提示',
                content: '上传图片失败',
                showCancel: false
              })
            }
          });
        })
      }
    }
  }

  handleChange (value) {
    const {formData} = this.state;
    formData.description = value;
    this.setFormData(formData)
  }

  editShow() {
    const {editShow} = this.state
    this.setState({editShow: !editShow})
  }

  async submitForm() {
    const {fileList1, formData} = this.state;
    formData.pictures = ''
    fileList1.map((item, index) => {
      formData.pictures += item.url + ','
    })
    // formData.pictures = 'https://resource.ivcheng.com/upload/2022/04/11/580b7b50b8824eb5a49e3704e626c69f.jpg,'
    const res = await http.HPost(AIKUCUN_ORDER_CREATAFTERSALE, formData)
    if (res) {
      if (res.message) {
        Taro.showToast({
          title: res.message,
          icon: 'none'
        })
      }
      if (res.data === '创建成功') {
        Taro.showToast({title: '提交成功'});
        const timer = setTimeout(() => {
          clearTimeout(timer);
          Taro.navigateTo({ url: '/main/order/aftersales/orderdetail?orderId=' + formData.order_num  })
        }, 1500);
      }
    }
  }

  render() {
    const {
      orderInfo,
      isReceived,
      formData,
      refundReason,
      fileList,
      editShow
    } = this.state
    if (!orderInfo) return
    return (
      <View className='after-sales-refund'>
        <View className='goods'>
          <View className='goods-title'>退款商品</View>
          <View className='goods-info'>
            <Image
              src={orderInfo.default_img_url}
            />
            <View>
              <View className='goods-info-title'>{orderInfo.product_name}</View>
              <View className='goods-info-price'>
                <View>
                  <View className='price'><Text className='symbol'>￥</Text><View className='view-inline'><Float
                    value={orderInfo.total_fee}
                  /></View></View>
                </View>
                <View className='goods-info-num'>
                  x{orderInfo.buy_amount}
                </View>
              </View>
            </View>
          </View>
        </View>

        <View className='info'>
          {Number(formData.application_type) === 2 && <View className='info-item'>
            <Picker
              mode='selector'
              range={isReceived}
              rangeKey='label'
              onChange={({detail: {value}}) => this.onChange(isReceived[value].value)}
              value={formData.is_received}
            >
              <View className='product-form-block-item border-bottom'>
                <View className='product-form-block-item-left require'>
                  货物状态
                </View>
                <View className='product-form-block-item-right t-a-r'>
                  {!formData.is_received && <View className='mepty'>
                    请选择
                    <AtIcon value='chevron-right' size='15' color='#b6b7b8' className='type-icon' />
                  </View>}
                  {formData.is_received && <View className='value c-666'>
                    {this.getName(formData.is_received)}
                  </View>}
                </View>
              </View>
            </Picker>
          </View>}

          <View className='info-item'>
            <Picker
              mode='selector'
              range={refundReason}
              rangeKey='label'
              onChange={({detail: {value}}) => this.onChangeReason(refundReason[value].value)}
              value={formData.refund_reason}
            >
              <View className='product-form-block-item border-bottom'>
                <View className='product-form-block-item-left require'>
                  退款原因
                </View>
                <View className='product-form-block-item-right t-a-r'>
                  {!formData.refund_reason && <View className='mepty'>
                    请选择
                    <AtIcon value='chevron-right' size='15' color='#b6b7b8' className='type-icon' />
                  </View>}
                  {formData.refund_reason && <View className='value c-666'>
                    {this.getNameReason(formData.refund_reason)}
                  </View>}
                </View>
              </View>
            </Picker>
          </View>

          <View className='info-item'>
            <View className='product-form-block-item'>
              <View className='product-form-block-item-left require'>
                退款金额
              </View>
            </View>
            <View className='refund-money'>
              <Text>￥</Text>
              {!editShow && <View className='value'>
                <Text>{formData.amount}</Text>
              </View>}
              {editShow && <View className='valueh5'>
                <Input
                  onInput={({detail: {value}}) => {
                    const {formData} = this.state;
                    formData.amount = value;
                    this.setFormData(formData);
                  }}
                  value={formData.amount}
                />
              </View>}
              {!editShow && <View className='edit-icon' onClick={() => this.editShow()}>
                <AtIcon value='edit' size='15' color='#666' className='type-icon' />
                修改
              </View>}
            </View>
          </View>

        </View>

        <View className='detail'>
          <View className='detail-title'>补充描述和凭证</View>

          <View className='detail-detail'>
            <View className='detail-detail-word'>
              <View className=''>
                <View className=''>
                  <AtTextarea
                    className='textarea'
                    count={false}
                    value={formData.description}
                    onChange={this.handleChange.bind(this)}
                    maxLength={200}
                    placeholder='补充描述，有助于商家更好的处理售后问题'
                  />
                </View>
              </View>
              <View className='detail-detail-word-limit'>0/200</View>
            </View>

            {process.env.TARO_ENV === 'weapp' &&
            <View className='product-form-block-gounp border-bottom'>
              <AtImagePicker
                files={fileList}
                onChange={this.onFileChange.bind(this)}
                multiple
                count={3}
              />
            </View>}
            {process.env.TARO_ENV === 'h5' &&
            <View className='product-form-block-gounp border-bottom'>
              {
                fileList && fileList.map((item, imageIndex) =>
                  <View className='_image-border'>
                    <View className='_close' onClick={(e) => {
                      const list = JSON.parse(JSON.stringify(fileList));
                      list.splice(imageIndex, 1);
                      this.onFileChange(list, {}, imageIndex);
                      e.stopPropagation();
                    }}
                    >
                      <Text className='_font'>
                        x
                      </Text>
                    </View>
                    <Image src={item.url} className='_image'></Image>
                  </View>
                )
              }
              <View className='image-border' onClick={() => this.onFileChange()}>
                <View className='add'>+</View>
              </View>
            </View>}
          </View>
        </View>

        <View className='footer'>
          <View className='btn-box-item' onClick={() => this.submitForm()}>
            提交信息
          </View>
        </View>
      </View>
    )
  }
}
